﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using JobSeek.Classes;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;



namespace JobSeek.Poster
{
    public partial class Upload : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Form.Attributes.Add("enctype", "multipart/form-data");
        }
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            string guid;

            if (Session["guid"] == null)
            {
                guid = Guid.NewGuid().ToString();
                Session["guid"] = guid;
            }
            else
            {
                guid = Session["guid"].ToString();
            }
            if (AsyncFileUpload1.HasFile && AsyncFileUpload1.FileContent.Length <= 2097152 && ImageControl.CheckFileContentType(AsyncFileUpload1.PostedFile.ContentType.ToLower()))
            {

                toggleOn();

                string filePath = @"~/_temp/" + guid;
                string filename = AsyncFileUpload1.FileName.Substring(AsyncFileUpload1.FileName.LastIndexOf("//") + 1, AsyncFileUpload1.FileName.LastIndexOf("."));
                //crop's filename
                string destination = filePath + "/crop_" + filename + ".png";

                System.Drawing.Image upBmp = Bitmap.FromStream(AsyncFileUpload1.PostedFile.InputStream);

                if (!Directory.Exists(Server.MapPath(filePath)))
                {
                    Directory.CreateDirectory(Server.MapPath(filePath));
                }
                
                ImageControl.ScaleImage(upBmp, destination, 220, 320);
                imgCurrent.ImageUrl = destination;

                tbxRenameLogo.Text = (filename.Length > 20) ? filename.Substring(0, 20) : filename;
                errorPannel.Attributes.Add("style", "display:none");
                RegisterScript();
                ScriptManager.RegisterHiddenField(btnUpload, "crop", "");
            }
            else
            {
                //toogle the error panel to show the errors
                errorPannel.Attributes.Add("style", "display:block; padding: 20px;");


                errorPannel.Controls.Add(new LiteralControl("Please make sure that the file is less than 2MB."));
                errorPannel.Controls.Add(new LiteralControl("<br/>"));

                errorPannel.Controls.Add(new LiteralControl("Image formats accepted are: jpg, png, bmp, gif."));


            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            if (this.Request.Form["crop"] != null)
            {
                string destination = "";
                string filePath = Server.MapPath(imgCurrent.ImageUrl);

                //request for the crop dimensions
                int[] dimensions = RequestCropDimension();

                if (dimensions == null)
                {
                    return;
                }

                System.Drawing.Image img = Bitmap.FromFile(Server.MapPath(imgCurrent.ImageUrl));

                string imageFolder = @"~/_temp/" + Session["guid"].ToString();

                string name = tbxRenameLogo.Text;

                destination = imageFolder + "/" + name + ".png";
                ImageControl.CropImage(img, destination, imgCurrent.ImageUrl , dimensions[0], dimensions[1], dimensions[2], dimensions[3], 131, 131, "png");


                toggleOff();

                Logo logo = new Logo();
                logo.name = name;
                logo.width = 131;
                logo.height = 131;
                logo.logo_url = destination;
                logo.isUsed = false;


                if (Session["logos"] == null)
                {
                    List<Logo> images = new List<Logo>();
                    AddLogoToList(logo, images);

                }
                else
                {
                    List<Logo> images = (List<Logo>)Session["logos"];
                    AddLogoToList(logo, images);
                }

                //now we have to display the image on the carousel
                DisplayLogoOnRepeater();
            }

            RegisterScript();
        }
        /// <summary>
        /// Request the crop dimension from the hidden field. Cast everything to int before sending the value back. 
        /// </summary>
        /// <returns>An array of cropped dimensions</returns>
        private int[] RequestCropDimension()
        {
            try
            {
                string cropDimension = this.Request.Form["crop"];

                cropDimension = cropDimension.Substring(cropDimension.IndexOf('(') + 1);
                cropDimension = cropDimension.Substring(0, cropDimension.LastIndexOf(')'));

                string[] dimensions = cropDimension.Split(',');
                int[] _dimensions = new int[4];
                for (int i = 0; i < dimensions.Length; i++)
                {
                    _dimensions[i] = Convert.ToInt32(dimensions[i]);
                }
                return _dimensions;
            }
            catch (Exception ex)
            {
                //Log error file
                return null;
            }
        }
        private void AddLogoToList(Logo logo, List<Logo> images)
        {
            if (!images.Contains(logo, new CustomComparer()))
            {
                images.Add(logo);
                Session["logos"] = images;
            }
            else
            {
                int index = -1;
                for (int i = 0; i < images.Count; i++)
                {
                    if (images[i].name == logo.name)
                    {
                        index = i;
                        break;
                    }
                }
                images.RemoveAt(index);
                images.Add(logo);
                Session["logos"] = images;
            }
        }

        public void RegisterScript()
        {
            StringBuilder scriptBuilder = new StringBuilder();

            scriptBuilder.Append("var image = $('#imgCurrent');");
            scriptBuilder.Append("var originalRatio = image.width() / image.height(); ");
            scriptBuilder.Append("var previewMaxHeight =131;   var previewMaxWidth =131; ");
            scriptBuilder.Append("var divPreview = $('#preview'); divPreview.css({width: previewMaxWidth + 'px', height: previewMaxHeight + 'px', overflow: 'hidden' });");



            //  script += " var innerPreview = $('<div />').css({  overflow: 'hidden' }).attr('id', 'innerPreview').appendTo(divPreview);";
            scriptBuilder.Append(" var innerPreview = $('#innerPreview');");

            //script += " $('<img />').attr('src', image.attr('src')).appendTo(innerPreview);";
            scriptBuilder.Append(" $('#croppedImage').attr('src', image.attr('src'));");
            // script += "  jcrop_api.animateTo(new Array(0,0,image.width(), image.height()));";
            scriptBuilder.Append("update({ x: 0, y: 0, x2: image.width(), y2: image.height(), w: image.width(), h: image.height() });");
            scriptBuilder.Append("$('#mycarousel').jcarousel({});");

            Page.ClientScript.RegisterStartupScript(Page.GetType(), "CropScript", scriptBuilder.ToString(), true);
        }

        public void DisplayLogoOnRepeater()
        {

            Repeater1.DataSource = (List<Logo>)Session["logos"];
            Repeater1.DataBind();



        }

        protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            foreach (Control c in e.Item.Controls)
            {
                if (c.GetType() == typeof(System.Web.UI.WebControls.Image))
                {
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)c;
                    Logo image = (Logo)e.Item.DataItem;
                    double carouselHeight = 50;
                    double carouselWidth = 50;

                    double newWidth = 50;
                    double newHeight = 50;
                    if (image.width > image.height)
                    {
                        double reduceBy = carouselWidth / image.width;
                        newHeight = image.height * reduceBy;


                    }
                    else if (image.width < image.height)
                    {
                        double reduceBy = carouselHeight / image.height;

                        newWidth = image.width * reduceBy;
                    }
                    else
                    {
                        double reduceBy = carouselHeight / image.height;
                        newHeight = image.height * reduceBy;
                        newWidth = image.width * reduceBy;
                    }

                    img.Width = new Unit(newWidth);
                    img.Height = new Unit(newHeight);
                }
            }
        }
        private void toggleOn()
        {
            togglePanel.Attributes.Add("style", "display:block");

        }

        private void toggleOff()
        {
            togglePanel.Attributes.Add("style", "display:none");

            //lblRenameLogo.Attributes.Add("style", "display:none");
            // tbxRenameLogo.Attributes.Add("style", "display:none");
        }

       
    }

}